package com.wp.编程之法.chapter1;

import java.util.*;

/**
 * Created by 王萍 on 2017/4/4 0004.
 */
public class 字符串包含 {

    public static void main(String[] args) {

//        String s1 = "bcaat";
//        String s2 = "acbat";
//
//        System.out.println(checkBrother(s1.toCharArray(), s2.toCharArray()));

        String s1 = "aBCD"; //为true
//        String s1 = "ABCD";
        String s2 = "A";
        System.out.println('a' - 'A');  // 32
        System.out.println(1 << 32);  // 1

        System.out.println(stringContain(s1, s2));
    }

    /**
     * 通过位运算将字母映射到一种二进制描述的表中，类似Hash表
     * 无法识别大小写。
     * 当字符串“AABD”中，出现第二次A时，对hash值没有改变。
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean stringContain(String a, String b) {
        int hash = 0;
        for (int i = 0; i < a.length(); i++) {
            System.out.println(1 << (a.charAt(i) - 'A'));
            hash |= (1 << (a.charAt(i)) - 'A');
        }
        for (int i = 0; i < b.length(); i++) {
            hash &= (1 << (b.charAt(i)) - 'A');
            if (hash == 0) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkBrother(char[] s1, char[] s2) {

        HashMap<Character, Integer> map = new HashMap<>();

        for (char s : s1) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }

        for (char s : s2) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) - 1);
            }
        }



        Collection<Integer> values = map.values();
        int count = 0;
        Iterator<Integer> iterator = values.iterator();

        while (iterator.hasNext()) {
            count += Math.abs(iterator.next());
        }
        if (count != 0) {
            return false;
        }
        return true;
    }
}
